// pages/publish/list/list.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 0,
    products: [],
    statusCounts: {
      total: 0,
      onSale: 0,    // 在售
      trading: 0,   // 交易中
      sold: 0,      // 已售出
      offline: 0    // 已下架
    },
    loading: false,
    page: 1,
    totalPages: 1,
    statusMap: ['', '在售', '交易中', '已售出', '已下架']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadProducts();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({ page: 1 }, () => {
      this.loadProducts().then(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.page < this.data.totalPages && !this.data.loading) {
      this.setData({ page: this.data.page + 1 }, () => {
        this.loadProducts(true);
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  async loadProducts(append = false) {
    try {
      this.setData({ loading: true });
      const status = this.data.statusMap[this.data.activeTab];

      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/products/user`,
          method: 'GET',
          data: {
            status: status,
            page: this.data.page,
            limit: 10
          },
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: resolve,
          fail: reject
        });
      });

      const { products, total, totalPages } = response.data.data;

      // 转换状态计数
      const statusCounts = {
        total: response.data.data.statusCounts.total || 0,
        onSale: response.data.data.statusCounts['在售'] || 0,
        trading: response.data.data.statusCounts['交易中'] || 0,
        sold: response.data.data.statusCounts['已售出'] || 0,
        offline: response.data.data.statusCounts['已下架'] || 0
      };

      this.setData({
        products: append ? [...this.data.products, ...products] : products,
        statusCounts,
        totalPages,
        loading: false
      });
    } catch (error) {
      console.error('加载商品列表失败:', error);
      Toast.fail('加载失败');
      this.setData({ loading: false });
    }
  },

  onTabChange(event) {
    this.setData({
      activeTab: event.detail.index,
      page: 1,
      products: []
    }, () => {
      this.loadProducts();
    });
  },

  async deleteProduct(event) {
    const { id } = event.currentTarget.dataset;

    Dialog.confirm({
      title: '确认删除',
      message: '确定要删除这个商品吗？'
    }).then(async () => {
      try {
        await new Promise((resolve, reject) => {
          wx.request({
            url: `${app.globalData.baseUrl}/api/products/${id}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${wx.getStorageSync('token')}`
            },
            success: resolve,
            fail: reject
          });
        });

        Toast.success('删除成功');
        this.loadProducts();
      } catch (error) {
        console.error('删除商品失败:', error);
        Toast.fail('删除失败');
      }
    });
  },

  editProduct(event) {
    const { id } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/publish/edit/edit?id=${id}`
    });
  }
})